package com.mc.web.controller.clt;

import com.alibaba.fastjson.JSONObject;
import com.mc.clt.constant.Constants;
import com.mc.clt.domain.*;
import com.mc.clt.service.ICltPositionService;
import com.mc.clt.service.ICltService;
import com.mc.clt.service.ICltTaskService;
import com.mc.common.annotation.Log;
import com.mc.common.core.controller.BaseController;
import com.mc.common.core.domain.AjaxResult;
import com.mc.common.core.domain.entity.SysUser;
import com.mc.common.core.domain.model.LoginUser;
import com.mc.common.core.page.TableDataInfo;
import com.mc.common.enums.BusinessType;
import com.mc.common.utils.DateUtils;
import com.mc.common.utils.ServletUtils;
import com.mc.framework.web.service.TokenService;
import com.mc.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/mapper/clt")
@Api("野外采集")
public class CltController extends BaseController {

    @Autowired
    private ICltTaskService cltTaskService;

    @Autowired
    private ICltPositionService cltPositionService;

    @Autowired
    private ICltService cltService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @ApiOperation("获取采集任务列表")
    @PreAuthorize("@ss.hasPermi('clt:task:list')")
    @GetMapping("/task/list")
    public TableDataInfo taskList(CltTask cltTask){
        startPage();
//        if(cltTask.getState()==null||"".equals(cltTask.getState())){
//            cltTask.setState("0");
//        }
        List<CltTask> list = cltTaskService.selectCltTaskStatisticalList(cltTask);
        return getDataTable(list);
    }

    @ApiOperation("根据采集任务ID查询采集信息")
    @PreAuthorize("@ss.hasPermi('clt:task:list')")
    @GetMapping("/task/result/{id}")
    public TableDataInfo resultListByTaskID(@PathVariable("id") String id){
        startPage();
        return getDataTable(cltService.selectCltResultByTaskId(id));

    }

    /**
     * 根据ID查询采集任务
     * @param id
     * @return
     */
    @ApiOperation("获取采集任务详细")
    @PreAuthorize("@ss.hasPermi('clt:task:query')")
    @GetMapping(value = "/task/{id}")
    public AjaxResult getTaskInfo(@PathVariable("id") String id){
        return AjaxResult.success(cltTaskService.selectCltTaskById(id));
    }

    /**
     * 禁用采集任务
     * @param id
     * @return
     */
    @ApiOperation("禁用采集任务")
    @PreAuthorize("@ss.hasPermi('clt:task:disable')")
    @GetMapping(value = "/task/disable/{id}")
    public AjaxResult disableTask(@PathVariable("id") String id){
        return AjaxResult.success(cltTaskService.deleteCltTaskById(id));
    }

    @ApiOperation("获取采集任务")
    @PreAuthorize("@ss.hasPermi('clt:task:list')")
    @GetMapping(value = "/task/user")
    public TableDataInfo list(SysUser user){
        startPage();
        List<SysUser> list = userService.selectUserByTaskList(user);

        return getDataTable(list);
    }

    /**
     * 新增采集任务
     * @param cltTask
     * @return
     */
    @ApiOperation("新增采集任务")
    @ApiImplicitParam(name = "cltTask", value = "新增用户信息", dataType = "CltTask")
    @PreAuthorize("@ss.hasPermi('clt:task:add')")
    @Log(title = "新增采集任务", businessType = BusinessType.INSERT)
    @PostMapping(value = "/task/add")
    public AjaxResult addTask(@RequestBody CltTask cltTask){
        //JSONObject usersJson = JSONObject.parseObject(jsonParam.getString("users"));

        if(cltTaskService.selectCltTaskByTaskName(cltTask.getTaskName())>0){
            return AjaxResult.error("采集任务已存在");
        }

        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        cltTask.setId(uuid);
        cltTask.setState("0");
        List<CltTaskUser> photoList = cltTask.getUsers();

        return AjaxResult.success(cltTaskService.insertCltTask(cltTask,photoList));
    }

    /**
     * 修改采集任务
     * @param cltTask
     * @return
     */
    @ApiOperation("修改采集任务")
    @ApiImplicitParam(name = "cltTask", value = "新增用户信息", dataType = "CltTask")
    @PreAuthorize("@ss.hasPermi('clt:task:add')")
    @Log(title = "修改采集任务", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/task/edit")
    public AjaxResult editTask(@RequestBody CltTask cltTask){
        //cltTask.setState("0");
        List<CltTaskUser> usersoList = cltTask.getUsers();
        return AjaxResult.success(cltTaskService.updateCltTask(cltTask,usersoList));
    }

    /**
     * 查询在线人数
     */
    @ApiOperation("查询在线人数")
    @PreAuthorize("@ss.hasPermi('clt:position:query')")
    @GetMapping(value = "/online/position")
    public AjaxResult position (){

        return AjaxResult.success(cltPositionService.selectLastCltResult(Constants.lastLogin));
    }

    @ApiOperation("查询轨迹")
    @PreAuthorize("@ss.hasPermi('clt:position:list')")
    @GetMapping(value = "/online/position/list")
    public TableDataInfo positionList (CltPosition cltPosition){
        //后期判断设备号
        startPage();
        return getDataTable(cltPositionService.selectCltResultList(cltPosition));
    }

    @ApiOperation("查询轨迹")
    @GetMapping(value = "/online/position/list1")
    public TableDataInfo positionList1 (CltPosition cltPosition){
        //后期判断设备号
        startPage();
        return getDataTable(cltPositionService.selectCltResultList(cltPosition));
    }


    /**
     * 滚动显示采集记录
     */
    @ApiOperation("实时滚动显示采集记录")
    @PreAuthorize("@ss.hasPermi('clt:real:query')")
    @PostMapping(value = "/real/result")
    public AjaxResult realTimeGetClt (@RequestBody JSONObject jsonObject){
        String date = jsonObject.getString("date");
        List<CltResult> list = new ArrayList<CltResult>();
        if(date==null||"".equals(date)){
            list = cltService.selectCltAll(Constants.NUM);
        }else{
            list = cltService.selectCltByDate(date);
        }
        return AjaxResult.success(list);
    }
    /**
     * 添加采集
     */
    @ApiOperation("添加采集")
    @PreAuthorize("@ss.hasPermi('clt:result:add')")
    @PostMapping(value = "/add/result/{type}")
    public AjaxResult addResult(@PathVariable String type,@RequestBody JSONObject jsonParam){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if(type.equals(Constants.GERMPLASM)){
            CltResultGermplasm germplasm = JSONObject.parseObject(jsonParam.toString(),CltResultGermplasm.class);
            germplasm.setCreateTime(DateUtils.getNowDate());
            germplasm.setCreateUserId(loginUser.getUsername());
            cltService.insertCltResultGermplasm(germplasm);
        }else if(type.equals(Constants.SPECIMEN)){
            CltResultSpecimen specimen = JSONObject.parseObject(jsonParam.toString(),CltResultSpecimen.class);
            specimen.setCreateTime(DateUtils.getNowDate());
            specimen.setCreateUserId(loginUser.getUsername());
            cltService.insertCltResultSpecimen(specimen);
        }else{
            return AjaxResult.error("采集类型不存在");
        }
        return AjaxResult.success("上传成功");
    }

    /**
     * 根据ID查询采集任务
     * @param id
     * @return
     */
    @ApiOperation("根据ID查询采集任务")
    @PreAuthorize("@ss.hasPermi('clt:result:query')")
    @GetMapping(value = "/result/id/{id}")
    public AjaxResult getResultById(@PathVariable String id){

        CltResult cltResult = cltService.selectCltResult(id);
        if(cltResult.getCltType().equals(Constants.GERMPLASM)){
            return AjaxResult.success(cltService.selectGermplasmByCltID(id));
        }else if(cltResult.getCltType().equals(Constants.SPECIMEN)){
            return AjaxResult.success(cltService.selectSpecimenByCltID(id));
        }else{
            return AjaxResult.error("采集编号有误");
        }
    }
    /**
     * 根据采集任务查询采集列表
     * @param cltInfo
     * @return
     */
    @ApiOperation("根据采集任务查询采集列表")
    @PreAuthorize("@ss.hasPermi('clt:result:list')")
    @GetMapping(value = "/resultByTaskId")
    public TableDataInfo getResultById(CltInfo cltInfo){

        String taskId = cltInfo.getTaskId();
        String taskType = cltInfo.getTaskType();
//        CltResult cltResult = cltService.selectCltResult(id);
        if(taskType==null||taskType.equals("")){
            taskType = Constants.GERMPLASM;
        }
        if(taskType.equals(Constants.GERMPLASM)){
            startPage();
            List<CltResultGermplasm> list = cltService.selectCltResultGermplasmByTaskIdList(taskId);
            return getDataTable(list);
        }else if(taskType.equals(Constants.SPECIMEN)){
            startPage();
            return getDataTable(cltService.selectCltResultSpecimenByTaskId(taskId));
        }else{
            return getDataTable(new ArrayList<>());
        }
    }

    /**
     * 搜索框查询
     * @param cltInfo
     * @return
     */
    @ApiOperation("野外采集搜索")
    @PreAuthorize("@ss.hasPermi('clt:result:list')")
    @GetMapping(value = "/result/list")
    public TableDataInfo resultList(CltInfo cltInfo){

        if(cltInfo.getType().equals(Constants.GERMPLASM)){
            startPage();
            List<CltResultGermplasm> list = cltService.selectGermplasmByName(cltInfo);

            return getDataTable(list,cltService.countAllCltResult(cltInfo));
        }else if(cltInfo.getType().equals(Constants.SPECIMEN)){
            startPage();
            List<CltResultSpecimen> list = cltService.selectSpecimenByName(cltInfo);
            return getDataTable(list,cltService.countAllCltSpecimenResult(cltInfo));
        }else{
            return getDataTable(new ArrayList<>());
        }
    }
    /**
     * 查询采集统计信息
     * @param
     * @return
     */
    @ApiOperation("查询采集统计信息")
    @PreAuthorize("@ss.hasPermi('clt:statistics:list')")
    @GetMapping(value = "/statistics")
    public AjaxResult statistics(){
        Map<String,Integer> map = new HashMap<String,Integer>();
        CltInfo cltInfo = new CltInfo();
        map.put("cltResultCount",cltService.countAllCltResult(cltInfo));
        map.put("cltSpecies",cltService.countCltFamily());
        return AjaxResult.success(map);
    }
    /**
     * 查询采集统计信息
     * @param
     * @return
     */
    @ApiOperation("查询采集统计信息")
    @PreAuthorize("@ss.hasPermi('clt:statistics:list')")
    @GetMapping(value = "/statistics/{type}")
    public TableDataInfo Rank(@PathVariable String type,String name){
        startPage();
        if (type.equals("rank")) {
            return getDataTable(cltService.countCltRank(name));

        }else if(type.equals("species")){
            return getDataTable(cltService.countCltSpecies(name));
        }else{
            return getDataTable(new ArrayList<>());
        }
    }
}
